package com.leyou.auth.service.impl;

import com.leyou.auth.constants.JwtConstants;
import com.leyou.auth.dto.Payload;
import com.leyou.auth.dto.UserDetail;
import com.leyou.auth.service.UserAuthService;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.common.exception.LyException;
import com.leyou.user.client.UserClient;
import com.leyou.user.dto.UserDTO;
import feign.FeignException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

@Service
public class UserAuthServiceImpl implements UserAuthService {
    @Autowired
    private  UserClient userClient;
    @Autowired
    private  JwtUtils jwtUtils;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public void login(String username, String password, HttpServletResponse response) {
        try {
           //授权中心携带用户账号密码   到用户中心查询用户
        UserDTO user = userClient.queryUserByUsernameAndPassword(username, password);
        //校验查询结果
        if (user==null){
            throw new LyException(400,"用户名或者密码错误");
        }
        //如果正确生成JWT凭证  如果错误 报400
        //准备用户信息
        UserDetail userDetails = UserDetail.of(user.getId(), user.getUsername());
        //生成jwt
        String jwt = jwtUtils.createJwt(userDetails);
        //把jwt写入cookie
            writeCookie( response,jwt);
        } catch (FeignException e) {
            //把远程调用异常抛出去
            throw  new LyException(e.status(),e.contentUTF8());
        }
    }

    @Override
    public void logout(String token, HttpServletResponse response) {
        Payload payload=jwtUtils.parseJwt(token);

        String username=payload.getUserDetail().getUsername();

        if (redisTemplate.hasKey(username)){
            redisTemplate.delete(username);
        }
        // 删除cookie
        addCookieToResponse(response,"",0);
    }

    @Override
    public UserDetail verifyUser(String token) {
        Payload payload=null;
        try {
            payload=jwtUtils.parseJwt(token);
        }catch (Exception e){
            throw new LyException(401,"登录状态有误");
        }
        return payload.getUserDetail();
    }

    private void addCookieToResponse(HttpServletResponse response,String info,Integer maxAge){
        Cookie cookie=new Cookie("LY_TOKEN",info);
        cookie.setDomain("leyou.com");
        cookie.setPath("/");
        //js可以操作cookie  设置httpOnly后   脚本无法识别到当前cookie
         cookie.setHttpOnly(true);
         response.addCookie(cookie);
     }
    public void writeCookie(HttpServletResponse response,String token){
        Cookie cookie=new Cookie(JwtConstants.COOKIE_NAME,token);
        //cookie作用域
        cookie.setDomain(JwtConstants.DOMAIN);
        //是否禁止JS操作cookie
        cookie.setHttpOnly(true);
        //cookie有效期
        cookie.setMaxAge(-1);
        //cookie作用路径
        cookie.setPath("/");
        response.addCookie(cookie);

    }
}
